package com.lanyam.travel.base.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class WXCodeUtil {
	
	
	/**
	 * 根据appid和secret获取微信授权用户的信息,包括openid和session_key
	 * @param appid
	 * @param secret
	 * @return
	 */
	public static String getWxLoginInfo(String appid,String secret,String code)
	{
		Logger logger = Logger.getLogger(WXCodeUtil.class);
		
		StringBuilder builder = new StringBuilder();
		BufferedReader bis = null;
		PrintWriter printWriter = null;
		try {

			URL url = new URL("https://api.weixin.qq.com/sns/jscode2session?grant_type=client_credential&appid=" + appid
					+ "&secret=" + secret + "&js_code=" + code);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setRequestMethod("GET");// 提交模式
			httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
			// 发送POST请求必须设置如下两行
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			printWriter = new PrintWriter(httpURLConnection.getOutputStream());
			// 发送请求参数
			JSONObject paramJson = new JSONObject();
			printWriter.write(paramJson.toString());
			// flush输出流的缓冲
			printWriter.flush();
			// 开始获取数据
			bis = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

			String len;
			while ((len = bis.readLine()) != null) {
				System.out.println(len);
				builder.append(len);
			}

		} catch (Exception e) {
			logger.error("获取微信授权用户信息失败："+e.getMessage());
		} finally {
			try {
				bis.close();
				printWriter.close();
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
		}
		return builder.toString();
	}
	/**
	 * 通过appid和secret获取session_key
	 * @param appid
	 * @param secret
	 * @return
	 */
	public static String getAccessToken(String appid,String secret,String code)
	{
		String result = getWxLoginInfo(appid, secret,code);
		if(!StringUtils.isEmpty(result))
		{
			JSONObject jsonObject = JSON.parseObject(result);
			return jsonObject.get("session_key").toString();
		}
		return null;
	}
	/**
	 * 通过appid和secret获取openId
	 * @param appid
	 * @param secret
	 * @return
	 */
	public static String getOpenId(String appid,String secret,String code)
	{
		String result = getWxLoginInfo(appid, secret,code);
		if(!StringUtils.isEmpty(result))
		{
			JSONObject jsonObject = JSON.parseObject(result.toString());
			return jsonObject.get("openid").toString();
		}
		return null;
	}
	/**
	 * 通过appid和secret获取access_token
	 * @param appid
	 * @param secret
	 * @return
	 */
	public static String getToken(String appid, String secret) {
		StringBuilder token = new StringBuilder("");
		JSONObject jsonObject = null;
		BufferedReader bis = null;
		PrintWriter printWriter = null;
		try {

			URL url = new URL("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid
					+ "&secret=" + secret);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setRequestMethod("GET");// 提交模式
			httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
			// 发送POST请求必须设置如下两行
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			printWriter = new PrintWriter(httpURLConnection.getOutputStream());
			// 发送请求参数
			JSONObject paramJson = new JSONObject();
			printWriter.write(paramJson.toString());
			// flush输出流的缓冲
			printWriter.flush();
			// 开始获取数据
			bis = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
			// OutputStream os = new FileOutputStream(new File(path));

			String len;
			while ((len = bis.readLine()) != null) {
				System.out.println(len);
				token.append(len);
			}
			jsonObject = JSON.parseObject(token.toString());

		} catch (Exception e) {
//			log.error(e.getMessage());
		} finally {
			try {
				bis.close();
				printWriter.close();
			} catch (IOException e) {
//				log.error(e.getMessage());
			}
		}
		return jsonObject.get("access_token").toString();
	}
	/**
	 * 通过appid和secret获取openId
	 * @param appid
	 * @param secret
	 * @return
	 */
	public static String getOpenId(String code) throws Exception
	{
		String AppID = Constant.APP_ID;
		String AppSecret=Constant.APP_SECRET;//这两个都可以从微信公众平台中查找
        
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
				+ AppID + "&secret=" + AppSecret + "&js_code=" + code + "&grant_type=authorization_code";
//		"https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
		URL reqURL = new URL(url);
		HttpsURLConnection openConnection = (HttpsURLConnection) reqURL
				.openConnection();
		openConnection.setConnectTimeout(10000);
		//这里我感觉获取openid的时间比较长，不过也可能是我网络的问题，
		//所以设置的响应时间比较长
		openConnection.connect();
		InputStream in = openConnection.getInputStream();

		StringBuilder builder = new StringBuilder();
		BufferedReader bufreader = new BufferedReader(new InputStreamReader(in));
		for (String temp = bufreader.readLine(); temp != null; temp = bufreader
				.readLine()) {
			builder.append(temp);
		}
		
		String result = builder.toString();
		in.close();
		openConnection.disconnect();
		JSONObject jsonObject = JSON.parseObject(result);

		return jsonObject.get("openid").toString();
		//result就是包含openid的键值对，返回给小程序前端即可
	}
	/**
	 * 获取指定长度的随机字符串
	 * @param length
	 * @return
	 */
    public static String getRandomStringByLength(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 获取请求中的ip
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }

}
